const {
    app,
    BrowserWindow,
    Menu,
    ipcMain,
    dialog} = require('electron')
const path = require('path')
const fs = require('fs')

let menuTemplate = [
    {
        label: '文件',
        submenu: [
            {
                label: '打开',
                accelerator: 'CmdOrCtrl+O',
                click: function(item,focusedWindow){
                    console.log('open file')
                    openFile();
                }
            }
        ]
    },
    {
        label: '编辑',
        submenu:[
            {
                label: '保存',
                accelerator: 'CmdOrCtrl+S',
                click: function(item,focusedWindow){
                    console.log('save file')
                    if(FILE_NAME===''){
                        return;
                    }
                    saveFile();
                }
            }
        ]
    }
];

let mainWin = null;
let FILE_NAME = '';

function createMainWindow() {
    mainWin = new BrowserWindow({
        width:800,
        height:600
    });

    mainWin.loadFile(path.join(__dirname,'client/index.html'));

    const menu = Menu.buildFromTemplate(menuTemplate);
    Menu.setApplicationMenu(menu);

    mainWin.webContents.openDevTools();

    mainWin.on('close',()=>{
        mainWin = null;
    })
}

app.on('ready',createMainWindow)

app.on('window-all-closed', () => {
    // 在 macOS 上，除非用户用 Cmd + Q 确定地退出，
    // 否则绝大部分应用及其菜单栏会保持激活。
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', () => {
    // 在macOS上，当单击dock图标并且没有其他窗口打开时，
    // 通常在应用程序中重新创建一个窗口。
    if (win === null) {
        createWindow()
    }
})

ipcMain.on('SAVE_TO_FILE',async function(event,data){
    console.log('SAVE_TO_FILE');
   let err = await witeFile(FILE_NAME,data);
})


function openFile(){
    dialog.showOpenDialog({
        title: '选择一个文件',
        properties: ['openFile'],
        buttonLabel: '打开',
        filters: [
            {name: 'text', extensions: ['txt']}
        ]
    },async function(files){
        if(files){
            console.log(files);
            FILE_NAME = files[0];
            let text = await readFile(files[0]);
            mainWin.webContents.send('OPEN_FILE_DATA', text);
        }
    })
}

function saveFile(){
    mainWin.webContents.send('SAVE_FILE_DATA');
}



function readFile(fileName){
    return new Promise((resolve,reject)=>{
        fs.readFile(fileName,(err,data)=>{
            if(err)reject(err);
            resolve(data.toString());
        })
    });
}

function witeFile(fileName,data){
    return new Promise((resolve,reject)=>{
        fs.writeFile(fileName,data,err=>{
            if(err)reject(err);
            resolve(null);
        });
    });
}